/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.controller;

import cw.controller.exceptions.IllegalOrphanException;
import cw.controller.exceptions.NonexistentEntityException;
import cw.controller.exceptions.PreexistingEntityException;
import cw.entity.Subject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import cw.entity.Puzzle;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 * @author VinhTC
 */
public class SubjectJpaController {

    public SubjectJpaController() {
        emf = Persistence.createEntityManagerFactory("CrossWordsAdminPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Subject subject) throws PreexistingEntityException, Exception {
        if (subject.getPuzzleList() == null) {
            subject.setPuzzleList(new ArrayList<Puzzle>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Puzzle> attachedPuzzleList = new ArrayList<Puzzle>();
            for (Puzzle puzzleListPuzzleToAttach : subject.getPuzzleList()) {
                puzzleListPuzzleToAttach = em.getReference(puzzleListPuzzleToAttach.getClass(), puzzleListPuzzleToAttach.getPuzzleId());
                attachedPuzzleList.add(puzzleListPuzzleToAttach);
            }
            subject.setPuzzleList(attachedPuzzleList);
            em.persist(subject);
            for (Puzzle puzzleListPuzzle : subject.getPuzzleList()) {
                Subject oldSubjectOfPuzzleListPuzzle = puzzleListPuzzle.getSubject();
                puzzleListPuzzle.setSubject(subject);
                puzzleListPuzzle = em.merge(puzzleListPuzzle);
                if (oldSubjectOfPuzzleListPuzzle != null) {
                    oldSubjectOfPuzzleListPuzzle.getPuzzleList().remove(puzzleListPuzzle);
                    oldSubjectOfPuzzleListPuzzle = em.merge(oldSubjectOfPuzzleListPuzzle);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSubject(subject.getSubjectId()) != null) {
                throw new PreexistingEntityException("Subject " + subject + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Subject subject) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Subject persistentSubject = em.find(Subject.class, subject.getSubjectId());
            List<Puzzle> puzzleListOld = persistentSubject.getPuzzleList();
            List<Puzzle> puzzleListNew = subject.getPuzzleList();
            List<String> illegalOrphanMessages = null;
            for (Puzzle puzzleListOldPuzzle : puzzleListOld) {
                if (!puzzleListNew.contains(puzzleListOldPuzzle)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Puzzle " + puzzleListOldPuzzle + " since its subject field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Puzzle> attachedPuzzleListNew = new ArrayList<Puzzle>();
            for (Puzzle puzzleListNewPuzzleToAttach : puzzleListNew) {
                puzzleListNewPuzzleToAttach = em.getReference(puzzleListNewPuzzleToAttach.getClass(), puzzleListNewPuzzleToAttach.getPuzzleId());
                attachedPuzzleListNew.add(puzzleListNewPuzzleToAttach);
            }
            puzzleListNew = attachedPuzzleListNew;
            subject.setPuzzleList(puzzleListNew);
            subject = em.merge(subject);
            for (Puzzle puzzleListNewPuzzle : puzzleListNew) {
                if (!puzzleListOld.contains(puzzleListNewPuzzle)) {
                    Subject oldSubjectOfPuzzleListNewPuzzle = puzzleListNewPuzzle.getSubject();
                    puzzleListNewPuzzle.setSubject(subject);
                    puzzleListNewPuzzle = em.merge(puzzleListNewPuzzle);
                    if (oldSubjectOfPuzzleListNewPuzzle != null && !oldSubjectOfPuzzleListNewPuzzle.equals(subject)) {
                        oldSubjectOfPuzzleListNewPuzzle.getPuzzleList().remove(puzzleListNewPuzzle);
                        oldSubjectOfPuzzleListNewPuzzle = em.merge(oldSubjectOfPuzzleListNewPuzzle);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = subject.getSubjectId();
                if (findSubject(id) == null) {
                    throw new NonexistentEntityException("The subject with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Subject subject;
            try {
                subject = em.getReference(Subject.class, id);
                subject.getSubjectId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The subject with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Puzzle> puzzleListOrphanCheck = subject.getPuzzleList();
            for (Puzzle puzzleListOrphanCheckPuzzle : puzzleListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Subject (" + subject + ") cannot be destroyed since the Puzzle " + puzzleListOrphanCheckPuzzle + " in its puzzleList field has a non-nullable subject field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(subject);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Subject> findSubjectEntities() {
        return findSubjectEntities(true, -1, -1);
    }

    public List<Subject> findSubjectEntities(int maxResults, int firstResult) {
        return findSubjectEntities(false, maxResults, firstResult);
    }

    private List<Subject> findSubjectEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Subject.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Subject findSubject(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Subject.class, id);
        } finally {
            em.close();
        }
    }

    public int getSubjectCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Subject> rt = cq.from(Subject.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    /**
     * getLevelByName
     * @param sbjName
     * @return Subject
     */
    public Subject getSubjectByName(String sbjName) {
        Subject sbj = null;
        try {
            Query query = getEntityManager().createNamedQuery("Subject.findBySbjName");
            query.setParameter("sbjName", sbjName);

            sbj = (Subject) query.getSingleResult();
        } catch (Exception e) {
            while (sbj == null) {
                Query query = getEntityManager().createNamedQuery("Subject.findBySbjName");
                query.setParameter("sbjName", sbjName);

                sbj = (Subject) query.getSingleResult();
            }
            Logger.getLogger(LevelJpaController.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
        }
        return sbj;
    }
}
